﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using BulkUploadGovernanceFiles.Models;

namespace BulkUploadGovernanceFiles
{
    public class UploadProcessor
    {
        private string _statusMessage;
        private readonly IEnumerable<FileInfo> _fileCollection;
        private bool _deleteDiskFile;
        private readonly DiskFilesManagement _diskFilesManagement;
        private readonly MongoFileProcessor _mongoFileProcessor;

        public UploadProcessor()
        {
            _statusMessage = "";
            _diskFilesManagement = new DiskFilesManagement();
            _mongoFileProcessor = new MongoFileProcessor(_diskFilesManagement.GetFileStream);
            if (_diskFilesManagement.GetFilesInFolder() != null)
            {
                _fileCollection = _diskFilesManagement.GetFilesInFolder();
            }
            else
            {
                throw new FileNotFoundException(string.Format("Folder {0} does not contain pdf files. Add pdf file and try again", ConfigManagement.FilePath));
            }
        }

        public string StatusMessage
        {
            get { return _statusMessage; }
        }

        public IEnumerable<FileInfo> FileCollection
        {
            get { return _fileCollection; }
        }

        public async Task Process(bool deleteDiskFile, CancellationToken token, IProgress<int> progress, GovernancePdfType type)
        {
            _deleteDiskFile = deleteDiskFile;
            try
            {
                await ProcessFiles(token, progress, type);
            }
            catch (OperationCanceledException ex)
            {
                _statusMessage = "Operation canceled !";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private async Task ProcessFiles(CancellationToken token, IProgress<int> progress, GovernancePdfType type)
        {
            await Task.Run(() =>
            {
                var i = 0;
                foreach (var file in _fileCollection)
                {
                    
                    token.ThrowIfCancellationRequested();
                    _mongoFileProcessor.ProcessFile(file, type);
                    if (_deleteDiskFile)
                    {
                        _diskFilesManagement.DeleteFile(file);
                    }
                    progress.Report(++i);
                }
                lock (_statusMessage)
                {
                    _statusMessage = "Done";
                }
            }, token);
        }

        public void DeleteAllFiles(GovernancePdfType type)
        {
            _mongoFileProcessor.RemoveAll(type);
        }
    }
}
